package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"furni-home/cache"
	"furni-home/model"
	"time"

	"furni-home/homerpc/homerpc"
	"furni-home/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListHomeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListHomeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListHomeLogic {
	return &ListHomeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListHomeLogic) ListHome(in *homerpc.ListHomeRequest) (*homerpc.ListHomeResponse, error) {
	// todo: add your logic here and delete this line
	var home []model.HomeData
	result, _ := cache.Rdb.Get(cache.Ctx, "homeList").Result()
	if result == "" {
		err := model.DB.Debug().Model(&model.Home{}).
			Select("homes.*,classes.`name` AS class_name,brands.`name` AS brand_name").
			Joins("LEFT JOIN classes ON classes.id = homes.class_id").
			Joins("LEFT JOIN brands ON brands.id = homes.brand_id").
			Find(&home).Error
		if err != nil {
			return nil, fmt.Errorf("列表查询失败")
		}
		marshal, _ := json.Marshal(home)
		cache.Rdb.Set(cache.Ctx, "homeList", marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &home)
	}

	var homeData []*homerpc.HomeList
	for _, data := range home {
		list := homerpc.HomeList{
			Name:      data.Name,
			Price:     float32(data.Price),
			Stock:     data.Stock,
			Image:     data.Image,
			ClassName: data.ClassName,
			BrandName: data.BrandName,
			HomeId:    int64(data.ID),
		}
		homeData = append(homeData, &list)
	}
	return &homerpc.ListHomeResponse{
		List: homeData,
	}, nil
}
